<?php


namespace App\Services;


use Illuminate\Support\Facades\Redis;

class CopySmsService
{

    const MOBILE_LIMIT = 30;
    const IP_LIMIT = 30;
    const SMS_SEND_TYPE_OFFLINE = 'offline';

    ////智讯云老接口的状态码
    protected static $fail_short_msg = array(
        '-1' => '账号未注册', '-2' => '其他错误', '-3' => '帐号或密码错误', '-5' => '余额不足，请充值', '-6' => '定时发送时间不是有效的时间格式',
        '-7' => '提交信息末尾未签名，请添加中文的企业签名【 】', '-8' => '发送内容需在1到300字之间', '-9' => '发送号码为空',
        '-10' => '定时时间不能小于系统当前时间', '-100' => 'IP黑名单', '-102' => '账号黑名单', '-103' => 'IP未导入白名单'
    );
//智讯云新接口的状态码
//    protected static $fail_short_msg = array(
//        '0' => '发送成功', '9' => '失败', '429' => '请求过多', '999' => '余额不足，请充值', '1000' => '账号/密码错误',
//        '1001' => '手机号码错误', '1002' => '内容格式错误', '1003' => '模板id错误',
//        '1004' => '定时时间格式错误', '1005' => '自定义id不可超过36位', '1006' => '号码数已达上限', '1007' => '定时必须大于10分钟',
//        '10001' => '短信签名错误', '10008' => '未开通短信模板'
//    );
    public static function sendCode($mobile,$type='smsCode'){
        $LimitCheck = self::limitSend($mobile);
        if(!$LimitCheck){
            return ['status'=>false,'msg'=>'您今日获取短信验证码的次数过多'];
        }
        $code = rand(1000,9999);
        $message = '您的验证码为：'.$code.'，请于1分钟内正确输入，如非本人操作，请忽略此短信。';
        $send_res = self::send_msg($mobile,$message);
        if($send_res['status']){
            Redis::setEx($mobile.$type, 300, $code);
            return ['status'=>true,'msg'=>'发送成功'];
        }else{
            return ['status'=>false,'msg'=>$send_res['msg']];
        }
    }
//智讯云老接口的状态码
    public static function send_msg($mobile,$content)
    {
        header("Content-type: text/html; charset=utf-8");
        $uid = config('alipay.other.smsUid');
        $pwd = config('alipay.other.smsPwd');
        date_default_timezone_set('PRC'); //设置默认时区为北京时间
        $msg = rawurlencode(iconv("utf-8","GBK",$content.'【'.config('alipay.other.sms_sign').'】'));
        // $msg = rawurlencode(iconv("utf-8","GBK",$content));
//        $gateway="https://sdk2.028lk.com/sdk2/BatchSend2.aspx?CorpID={$uid}&Pwd={$pwd}&Mobile={$mobile}&Content={$msg}&Cell=&SendTi";
        $gateway = "https://sdk3.028lk.com:9988/BatchSend2.aspx?CorpID={$uid}&Pwd={$pwd}&Mobile={$mobile}&Content={$msg}&Cell=&SendTime=";
        $result = file_get_contents($gateway);
        // echo '<pre>';
        // print_r($result);
        // dd(1);
        if ($result > 0) {
            return ['status'=>true,'msg'=>'发送成功'];
        } else {
            return ['status'=>false,'msg'=>self::$fail_short_msg[$result]];
        }
        /*$addData = array(
            "lease_id" => $v['ol_id'],
            "send_times" => 1,
            "mobile" => $mobile,
            "info" => $content,
            "status" => $send_msg['status'],
            "result" => $result,
            "result_msg" => $send_msg['result_msg'],
            "create_time" => date("Y-m-d H:i:s"),
            "update_time" => date("Y-m-d H:i:s"),
        );*/
    }
    //智讯云新接口的状态码
    /*发送短信*/
    public static function send_msg_new($mobile,$content){
        $url = "https://api.028lk.com/Sms/Api/Send";
        $SecretName = config('alipay.other.smsUid');
        $SecretKey = config('alipay.other.smsPwd');
        $SignName=config('alipay.other.sms_sign');
        $data = array(
            "SecretName" =>$SecretName,
            "SecretKey" => $SecretKey,
            "Mobile" => $mobile,
            "Content" => $content,
//            "TemplateId" => $TemplateId,
//            "ExtCode" => $ExtCode,
            "SignName" => '【'.$SignName.'】',
//            "Timing" => $Timing,
//            "CustomId" => $CustomId
        );
        $postData=json_encode($data);
        $postHeader=array(
            "Content-Type: application/json; charset=utf-8",
            "Content-Length:".strlen($postData)
        );
        //POST方式请求
        $curl = curl_init();
        //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查 -https
        //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$postHeader);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        $result= json_decode($output,true);dd($result);
        if ($result['code'] ==0) {
            return ['status'=>true,'msg'=>'发送成功'];
        } else {
            return ['status'=>false,'msg'=>self::$fail_short_msg[$result['code']]];
        }
    }
    /**
     * 验证码校验
     * @param $mobile
     * @param $code
     * @param string $type
     * @return bool
     */
    public static function checkCode($mobile,$code,$type='smsCode'){
        $smsCode = Redis::get($mobile.$type);
        if($code != $smsCode){
            return false;
        }
        return true;
    }

    public static function limitSend($mobile){
        $telNum = self::checkLimit('tel_',self::MOBILE_LIMIT,$mobile);
        $codeIpNum = self::checkLimit('codeIp_',self::IP_LIMIT,$_SERVER["REMOTE_ADDR"]);
        if ($telNum < self::MOBILE_LIMIT || $codeIpNum < self::IP_LIMIT) {
            return true;
        } else {
            return false;
        }
    }

    private static function checkLimit($key,$limit,$value)
    {
        $data = Redis::get(self::getLimitCodeKey($key));
        $c_sum = 0;
        if ($data) {
            $row = explode("|", $data);
            $countArr = array_count_values($row);
            if (isset($countArr[$value])) {
                if($countArr[$value] < $limit){
                    self::wirteData($key,$data.$value."|");
                }
                return $countArr[$value];
            }
        }
        self::wirteData($key,$data.$value."|");
        return $c_sum;
    }

    private static function getLimitCodeKey($key){
        return $key . date("Ymd");
    }
    private static function wirteData($key,$data){
        $tomorrow = strtotime(date("Y-m-d 00:00:00",strtotime("+1 day")));
        $sTime = $tomorrow - time();
        Redis::setEx(self::getLimitCodeKey($key), $sTime, $data);
    }



}
